import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card } from '@/components/ui/card';
import { CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { toast } from '@/components/ui/use-toast';
import { Github, Mail, Password, User, AlertCircle } from 'lucide-react';

const RegisterPage = () => {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [username, setUsername] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const validateForm = () => {
    if (!email || !password || !confirmPassword || !username) {
      setError('请填写所有必填字段');
      return false;
    }

    if (!email.includes('@')) {
      setError('请输入有效的邮箱地址');
      return false;
    }

    if (password.length < 8) {
      setError('密码长度至少为8个字符');
      return false;
    }

    if (password !== confirmPassword) {
      setError('两次输入的密码不一致');
      return false;
    }

    return true;
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      // 在实际应用中，这里会调用后端API进行注册
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password, username }),
      });

      if (response.ok) {
        toast({ title: '注册成功', description: '请登录您的账号' });
        router.push('/login');
      } else {
        const data = await response.json();
        setError(data.message || '注册失败，请稍后重试');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
      console.error('注册错误:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleGithubRegister = () => {
    // GitHub OAuth 注册流程
    window.location.href = '/api/auth/github';
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-4 sm:p-6 lg:p-8">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-primary mb-2">VisualDL Hub</h1>
          <p className="text-gray-500 dark:text-gray-400">创建您的账号，开始使用 AI 模型管理平台</p>
        </div>
        
        <Card className="shadow-lg border-0 dark:bg-gray-800 dark:text-gray-100 transition-all duration-300 hover:shadow-xl">
          <CardHeader>
            <CardTitle className="text-2xl text-center">创建账号</CardTitle>
            <CardDescription className="text-center">
              加入我们，管理和部署您的 AI 模型
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleRegister} className="space-y-4">
              {error && (
                <div className="flex items-start gap-2 p-3 rounded-md bg-red-50 text-red-500 dark:bg-red-950/50 dark:text-red-400">
                  <AlertCircle className="h-4 w-4 mt-0.5" />
                  <p className="text-sm font-medium">{error}</p>
                </div>
              )}
              
              <div className="space-y-2">
                <Label htmlFor="username" className="text-sm font-medium">
                  用户名
                </Label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <User className="h-4 w-4 text-gray-400" />
                  </div>
                  <Input
                    id="username"
                    type="text"
                    placeholder="输入您的用户名"
                    className="pl-10 transition-all duration-200 focus:ring-2 focus:ring-primary/20"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email" className="text-sm font-medium">
                  邮箱地址
                </Label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <Mail className="h-4 w-4 text-gray-400" />
                  </div>
                  <Input
                    id="email"
                    type="email"
                    placeholder="your@email.com"
                    className="pl-10 transition-all duration-200 focus:ring-2 focus:ring-primary/20"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="password" className="text-sm font-medium">
                  密码
                </Label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <Password className="h-4 w-4 text-gray-400" />
                  </div>
                  <Input
                    id="password"
                    type="password"
                    placeholder="至少8个字符"
                    className="pl-10 transition-all duration-200 focus:ring-2 focus:ring-primary/20"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="confirm-password" className="text-sm font-medium">
                  确认密码
                </Label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <Password className="h-4 w-4 text-gray-400" />
                  </div>
                  <Input
                    id="confirm-password"
                    type="password"
                    placeholder="再次输入密码"
                    className="pl-10 transition-all duration-200 focus:ring-2 focus:ring-primary/20"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                  />
                </div>
              </div>

              <Button
                type="submit"
                className="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="flex items-center justify-center space-x-2">
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    <span>注册中...</span>
                  </div>
                ) : (
                  '创建账号'
                )}
              </Button>
            </form>
          </CardContent>
          
          <div className="relative flex items-center justify-center px-6 py-2">
            <div className="absolute left-0 right-0 top-1/2 h-px bg-gray-200 dark:bg-gray-700" />
            <span className="relative px-3 bg-white dark:bg-gray-800 text-sm text-gray-500 dark:text-gray-400">
              或继续
            </span>
          </div>
          
          <CardFooter className="flex justify-center space-x-4 pb-6">
            <Button
              variant="secondary"
              className="flex items-center space-x-2 bg-white dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 border border-gray-200 dark:border-gray-600 transition-all duration-200"
              onClick={handleGithubRegister}
            >
              <Github className="h-5 w-5" />
              <span>GitHub</span>
            </Button>
            
            {/* 未来可以添加其他第三方登录选项 */}
          </CardFooter>
        </Card>
        
        <div className="mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
          已有账号？
          <button 
            onClick={() => router.push('/login')}
            className="font-medium text-primary hover:text-primary/80 transition-colors duration-200 ml-1"
          >
            登录
          </button>
        </div>
        
        <div className="mt-4 text-center text-xs text-gray-400">
          点击注册，即表示您同意我们的
          <a href="/terms" className="text-primary hover:underline">服务条款</a>
          和
          <a href="/privacy" className="text-primary hover:underline">隐私政策</a>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;